package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.TravelCondition;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.QueryObject;
import cn.wolfcode.wolf2w.query.TravelQueryObject;
import cn.wolfcode.wolf2w.repository.TravelMongoRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {
    
    @Autowired
    private TravelMongoRepository travelMongoRepository;
    @Autowired
    private MongoTemplate template;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IDestinationService destinationService;

    @Override
    public void save(Travel travel) {
        travel.setId(null);
        travelMongoRepository.save(travel);
    }

    @Override
    public void update(Travel travel) {
        travelMongoRepository.save(travel);
    }

    @Override
    public void delete(String id) {
        travelMongoRepository.deleteById(id);
    }

    @Override
    public Travel get(String id) {
        Travel travel = travelMongoRepository.findById(id).orElse(null);
        if(travel != null){
            UserInfo userInfo = userInfoService.get(travel.getUserId());
            Destination destination = destinationService.get(travel.getDestId());
            travel.setAuthor(userInfo);
            travel.setDest(destination);
        }
        return travel;
    }

    @Override
    public List<Travel> list() {
        return travelMongoRepository.findAll();
    }

    @Override
    public Page<Travel> query(TravelQueryObject qo) {
        // 创建查询对象
        Query query = new Query();

        // 获取出行时间 ,详情查看getDay 方法注解,理解为什么能获取到
        TravelCondition day = qo.getDay();
        // 把出行时间添加进查询条件
        if(day != null){
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }

        // 获取人均消费
        TravelCondition perExpend = qo.getPerExpend();
        // 把人均消费添加进查询条件
        if(perExpend != null){
            query.addCriteria(Criteria.where("perExpend").gte(perExpend.getMin()).lte(perExpend.getMax()));
        }



        // 添加通过destId 查询游记的条件
        if(StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }

        // 查询总条数
        long count = template.count(query, Travel.class);

        // 调用PageRequest 方法进行分页
        Pageable pageable = null;
        if(qo.getOrderType() == 1){
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                    Sort.Direction.DESC, "createTime");
        }else if (qo.getOrderType() == 2){
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                    Sort.Direction.DESC, "viewnum");
        }else {
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                    Sort.Direction.ASC, "_id");
        }

        // 给查询对象设置条件
        query.with(pageable);
        // 从mongodb 中查询符合条件的数据
        List<Travel> travels = template.find(query, Travel.class);

        // 因为每个游记都有用户信息,所以要进行维护
        for(Travel travel : travels){
            // 通过遍历查询出来符合条件的游记集合,获取到每篇游记的用户id
            UserInfo userInfo = userInfoService.get(travel.getUserId());
            // 把用户id set进对应的游记里
            travel.setAuthor(userInfo);
        }

        // 返回当前页数据,分页和总长度
        return new PageImpl<>(travels , pageable , count);
    }

    @Override
    public void saveOrUpdate(Travel travel) {
        // 1.目的地
        Destination destination = destinationService.get(travel.getDestId());
        travel.setDestName(destination.getName());
        // 2.用户id , 不建议这里设置,在表现层controller 做过了

        // 3.更新时间travel
        travel.setLastUpdateTime(new Date());
        if(StringUtils.hasLength(travel.getId())){

            this.update(travel);
        }else {
            // 创建时间
            travel.setCreateTime(new Date());
            this.save(travel);
        }
    }



    @Override
    public List<Travel> queryViewnumTop3(String destId) {
        Query query = new Query();
        if(StringUtils.hasLength(destId)){
            query.addCriteria(Criteria.where("destId").is(destId));
        }
        Pageable pageable = PageRequest.of(0,3 , Sort.Direction.DESC , "viewnum");
        query.with(pageable);

        return template.find(query , Travel.class);
    }

    @Override
    public void audit(String id, int state) {
        // 获取当前游记
        Travel travel = this.get(id);
        // 判断当前游记状态是不是空或者不是待审核状态
        if(travel == null){
            throw new LogicException("参数异常");
        }
        if(travel.getState() != Travel.STATE_WAITING){
            throw new LogicException("游记不是待审核状态,无法审核");
        }

        if(state == Travel.STATE_RELEASE){
            // 如果审核通过, 把状态设置成通过
            travel.setState(Travel.STATE_RELEASE);
            // 设置发布时间为当前时间
            travel.setReleaseTime(new Date());
            // 设置最后修改时间为当前时间
            travel.setLastUpdateTime(new Date());
            //做修改操作
            this.update(travel);

        }else if (state == Travel.STATE_REJECT){
            // 如果审核不通过,把状态设置成不通过
            travel.setState(Travel.STATE_REJECT);
            // 设置发布时间为null
            travel.setReleaseTime(null);
            // 设置最后修改时间为当前时间
            travel.setLastUpdateTime(new Date());
            //做修改操作
            this.update(travel);
        }
    }

    @Override
    public void updateStateBtn(String id, int state) {
        Travel travel = this.get(id);
        if(travel == null){
            throw new LogicException("参数异常");
        }
        travel.setState(Travel.STATE_WAITING);
        this.update(travel);
    }
}
